<?php

class ReservationsController extends AppController{

    var $components = array('RequestHandler');

	//Actions ne nécessitant pas d'authentification
    public function beforeFilter(){
        parent::beforeFilter();
    }

    //Autorisations
    public function isAuthorized($user) {

        //Seul l'administrateur peut ajouter/modifier/supprimer des réservations
        if (isset($user['role']) && $user['role'] === 'admin') {

            if ($this->action === 'admin_add')
                return true;
            if ($this->action === 'admin_edit')
                return true;
            if ($this->action === 'admin_delete')
                return true;
        }

        return parent::isAuthorized($user);
    }

    //Ajouter/Modifier réservation
    public function add() {
        $error = array('error' => 1);

        //On vérifie que l'utilisateur ne soit pas déjà inscrit à la séance choisie
        $userReservation = $this->Reservation->find('first', array(
            'conditions' => array(
                'Reservation.user_id' => $this->data['user_id'],
                'Reservation.seance_id' => $this->data['seance_id']
            )
        ));


        if(empty($userReservation))
        {
            if (!empty($this->data)) {
                //Enregistrement dans la base
                if ($this->Reservation->save($this->data)) {
                    $error = array('error' => 0);
                }
            }
        }
        elseif($this->data['place'] == $userReservation['Reservation']['place'])
        {
            $this->Reservation->delete($userReservation['Reservation']['id']);
            $error = array('error' => 2);
        }
        else
        {
            $this->request->data['id'] = $userReservation['Reservation']['id'];

            if (!empty($this->data)) {
                //Enregistrement dans la base
                if ($this->Reservation->save($this->data)) {
                    $error = array('error' => 0);
                }
            }
        }

        

        $this->RequestHandler->setContent('json', 'application/json');
        $message = json_encode($error);

        $this->layout = null;
        $this->set('message', $message);
	}
}
?>